<template>
  <div class="daoru">
    <el-card>
      <h3>员工导入</h3>
      <el-alert
        title="每次导入仅可添加1000名员工，姓名，手机，入职时间，聘用形式为必填项"
        type="warning"
        show-icon
      >
      </el-alert>
      <excel :beforeUpload="beforeUpload" :onSuccess="onSuccess"></excel>
    </el-card>
    <p class="bottom-text">copyright© 2018 iHRM 系统 版权所有</p>
  </div>
</template>

<script>
import { userbatch } from "@/api/employees";
export default {
  methods: {
    beforeUpload(file) {
      const less2m = file.size / 1024 / 1024 < 2;
      if (!less2m) {
        this.$message.error("文件大小超过了2M");
      }
      return less2m;
    },
    async onSuccess({ header, results }) {
      console.log(results);
      let obj = {
        入职日期: "timeOfEntry",
        姓名: "username",
        手机号: "mobile",
        工号: "workNumber",
        转正日期: "correctionTime",
      };
      let newobj = results.map((item) => {
        let obj2 = {};
        Object.keys(obj).forEach((subitem) => {
          if (
            obj[subitem] == "timeOfEntry" ||
            obj[subitem] == "correctionTime"
          ) {
            obj2[obj[subitem]] = this.formatData(item[subitem]);
          } else {
            obj2[obj[subitem]] = item[subitem];
          }
        });
        return obj2;
      });
      console.log(newobj);
      await userbatch(newobj);
      this.$message.success("上传成功！");
      this.$router.push("/employees");
    },
    formatData(days) {
      let timestemp = (days - 1) * 24 * 60 * 60 * 1000;
      let time = new Date(timestemp);
      time.setYear(time.getFullYear() - 70);
      return time;
    },
  },
};
</script>

<style lang='scss'>
.daoru {
  h3 {
    text-align: center;
  }

  .bottom-text {
    text-align: center;
    font-size: 13px;
    color: rgb(121, 116, 116);
  }
}
</style>